package com.flycms.web.front.rest;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.flycms.constant.CommonConst;
import com.flycms.constant.StatusConst;
import com.flycms.core.base.BaseController;
import com.flycms.core.entity.PagingParam;
import com.flycms.core.entity.RestDataVo;
import com.flycms.core.utils.web.utils.CommonUtils;
import com.flycms.module.comment.model.Comments;
import com.flycms.module.comment.model.FlyContentType;
import com.flycms.module.comment.model.OptionCount;
import com.flycms.module.comment.service.CollectsService;
import com.flycms.module.comment.service.CommentsService;
import com.flycms.module.user.model.User;

@RestController
@RequestMapping("/cm")
public class CommentController extends BaseController {

    private static final Logger logger = LogManager.getLogger(CommentController.class);
    
    @Autowired
    protected CommentsService commentsService;
    
    @Autowired
    protected CollectsService collectsService;
    
    /**
     * 获取评论
     * @param contentId
     * @param contentType
     * @param pageIndex
     * @param pageSize
     * @return
     * @author 沁言訫語
     */
    
    @GetMapping(value = {"/list/{contentType}/{contentId}", "/list/{contentType}"})
    public RestDataVo getCommentList(
            @PathVariable(value = "contentId", required = false) Long contentId,
            @PathVariable("contentType") String contentType,
            @RequestParam(value = "pageIndex", required = false) Integer pageIndex,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        Integer status = StatusConst.OPEN.value();
        RestDataVo rest = null;
        PagingParam paging = CommonUtils.validParam(pageIndex, pageSize);
        FlyContentType ct = CommonUtils.getContentType(contentType);
        if (ct == null) {
            return RestDataVo.ERROR("请检查传入参数，{0}:{1}", contentType, contentId + "");
        }
        try {
            List<Comments> commentList = commentsService.getCommentList(contentId, null, status,
                    paging.getOffset(), paging.getRows(), ct);
            int count = commentsService.getCommentCount(contentId, null, status, ct);
            rest = RestDataVo.PAGE(commentList, paging.getPageIndex(), paging.getPageSize(), count);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("获取评论异常");
        }
        return rest;
    }
    
    @PostMapping(value = {"/u/edit/{id}"})
    public RestDataVo editComment(@PathVariable Integer id, @RequestBody Comments comment) {
        RestDataVo rest = null;
        //改评论和状态、修改时间
//        try {
//            commentService.editComment(id, comment.getContent(), comment.getStatus(), new Date());
//            rest = RestDataVo.OK("修改成功");
//        } catch (Exception e) {
//            logger.error("", e);
//            rest = RestDataVo.ERROR("修改失败");
//        }
        return rest;
    }
    
    /**
     * 对内容进行评价
     * @param contentType
     * @param contentId
     * @param star
     * @param maps
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/u/add/{contentType}/{contentId}"})
    public RestDataVo addComment(@PathVariable("contentType") String contentType,
            @PathVariable("contentId") Long contentId,
            @RequestParam(value = "star", required = false) Float star,
            @RequestBody Map<String, Object> maps) {
        RestDataVo rest = null;
        Comments cm = new Comments();
        cm.setContentId(contentId);
        FlyContentType ct = null;
        if (maps != null && maps.containsKey("content")
                && maps.get("content") != null) {
            String content = CommonUtils.transToString(maps.get("content"));
            ct = CommonUtils.getContentType(contentType);
            if (StringUtils.isBlank(content) || ct == null) {
                return RestDataVo.ERROR("点赞失败，请检查传入参数，{0}:{1}", contentType, contentId + "");
            }
            cm.setContent(keywordFilter.doFilter(content));
            if (star != null && star > 0 && star <= 5) {
                cm.setStar(star);
            }
        } else {
            return RestDataVo.ERROR("缺少必要参数");
        }
        User toUser = null;
        String title = null;
        try {
            Object obj = collectsService.queryContentObject(contentId, ct);
            if (obj == null) {
                return RestDataVo.ERROR("评论的内容不存在");
            }
            toUser = CommonUtils.getOwner(obj);
            title = CommonUtils.getContentTitle(obj);
        } catch (Exception e) {
            logger.error("", e);
            return RestDataVo.ERROR("评论异常");
        }
        Long userId = getUserId();
        cm.setUserId(userId);
        cm.setStatus(CommonConst.COMMENT_OPEN);
        cm.setCreateTime(new Date());
        cm.setReply(0);
        cm.setTitle(title);
//        reply
        try {
            OptionCount o = commentsService.addComment(cm, ct);
            //
            if (!Objects.equals(ct, FlyContentType.INDUSTRY_APP)) {
                messageService.addSystemMessage(userId, toUser.getUserId(), ct.msg(),
                        CommonUtils.getCommentMessageModel(toUser.getUserName(), ct.msg(), cm.getContent()));
//                用户xxx点赞了你的文章/评论了你的文章：评论内容
            }
            rest = RestDataVo.OK(o);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("评论异常，" + e.getMessage());
        }
        return rest;
    }
    
    /**
     * 回复回答的评论
     * @param contentId
     * @param maps
     * @return
     * @author 沁言訫語
     */
    
    @PostMapping(value = {"/u/reply/answer/{id}"})
    public RestDataVo addReplyComment(
            @PathVariable("id") Integer id,
            @RequestBody Map<String, Object> maps) {
        RestDataVo rest = null;
        Comments cm = new Comments();
        if (maps != null && maps.containsKey("content")
                && maps.get("content") != null) {
            String content = CommonUtils.transToString(maps.get("content"));
            if (StringUtils.isBlank(content)) {
                return RestDataVo.ERROR("点赞失败，请检查传入参数");
            }
            cm.setContent(keywordFilter.doFilter(content));
        } else {
            return RestDataVo.ERROR("缺少必要参数");
        }
        Comments obj = null;
        try {
            obj = commentsService.queryCommentById(id, FlyContentType.ANSWER);
            if (obj == null) {
                return RestDataVo.ERROR("评论的主题不存在");
            }
        } catch (Exception e) {
            logger.error("", e);
            return RestDataVo.ERROR("评论异常");
        }
        Long userId = getUserId();
        cm.setUserId(userId);
        cm.setStatus(CommonConst.COMMENT_OPEN);
        cm.setCreateTime(new Date());
        cm.setReply(1);
        cm.setReplyCommentId(id);
        cm.setReplyUserId(obj.getUserId());
        cm.setContentId(obj.getContentId());
//        reply
        try {
            OptionCount o = commentsService.addComment(cm, FlyContentType.ANSWER);
            rest = RestDataVo.OK(o);
        } catch (Exception e) {
            logger.error("", e);
            rest = RestDataVo.ERROR("评论异常，" + e.getMessage());
        }
        try {
            messageService.addSystemMessage(userId, obj.getUserId(), FlyContentType.ANSWER.msg(),
                    CommonUtils.getCommentMessageModel(obj.getUserName(), FlyContentType.ANSWER.msg(), cm.getContent()));
        } catch (Exception e) {
            
        }
        return rest;
    }
    
}
